package thread.synchroCode;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

import static java.lang.Thread.sleep;

@Slf4j(topic = "c.TestCyclicBarrier")
public class _14TestCyclicBarrier {

  public static void main(String[] args) {
    ExecutorService service = Executors.newFixedThreadPool(3);
    CyclicBarrier barrier = new CyclicBarrier(2, ()-> {
      log.debug("task1, task2 finish...");
    });
    for (int i = 0; i < 3; i++) { // task1  task2  task1
      service.submit(() -> {
        log.debug("task1 begin...");
        try {
          sleep(1);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        try {
          barrier.await(); // 2-1=1
        } catch (InterruptedException | BrokenBarrierException e) {
          e.printStackTrace();
        }
      });
      service.submit(() -> {
        log.debug("task2 begin...");
        try {
          sleep(2);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        try {
          barrier.await(); // 1-1=0
        } catch (InterruptedException | BrokenBarrierException e) {
          e.printStackTrace();
        }
      });
    }
    service.shutdown();

  }

  private static void test1() {
    ExecutorService service = Executors.newFixedThreadPool(5);
    for (int i = 0; i < 3; i++) {
      CountDownLatch latch = new CountDownLatch(2);
      service.submit(() -> {
        log.debug("task1 start...");
        try {
          sleep(1);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        latch.countDown();
      });
      service.submit(() -> {
        log.debug("task2 start...");
        try {
          sleep(2);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        latch.countDown();
      });
      try {
        latch.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      log.debug("task1 task2 finish...");
    }
    service.shutdown();
  }
}
